<template>
  <div class="banner-manager">
    <!-- 顶部操作区 -->
    <el-card class="header-card">
      <div class="header-content">
        <div class="title-section">
          <h2>轮播图管理</h2>
          <el-tag type="success" effect="dark" class="count-tag">
            共 {{ BannerList.length }} 部影片
          </el-tag>
        </div>
        <div class="action-section">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索电影名称"
            prefix-icon="el-icon-search"
            clearable
            class="search-input"
            @clear="handleSearchClear"
          />
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="refreshData">刷新</el-button>
        </div>
      </div>
    </el-card>

    <!-- 数据统计卡片 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon">
                <i class="el-icon-picture"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ BannerList.length }}</div>
                <div class="stat-label">轮播图总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon blue">
                <i class="el-icon-view"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ getActiveCount() }}</div>
                <div class="stat-label">已启用</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon orange">
                <i class="el-icon-star-on"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ getHotCount() }}</div>
                <div class="stat-label">热门影片</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card" shadow="hover">
            <div class="stat-content">
              <div class="stat-icon purple">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ getRecentAddedCount() }}</div>
                <div class="stat-label">最近添加</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 轮播图预览 -->
    <el-card class="preview-card">
      <template #header>
        <div class="card-header">
          <h3>轮播图预览</h3>
          <el-switch
            v-model="previewEnabled"
            active-text="启用预览"
            inactive-text="关闭预览"
          ></el-switch>
        </div>
      </template>
      <div v-if="previewEnabled" class="carousel-container">
        <el-carousel
          :interval="4000"
          type="card"
          height="400px"
          indicator-position="outside"
          class="banner-carousel"
        >
          <el-carousel-item
            v-for="item in BannerList"
            :key="item.id"
            class="carousel-item"
          >
            <div class="carousel-content">
              <img :src="item.photo" alt="" class="carousel-image" />
              <div class="carousel-overlay">
                <h3 class="movie-title">{{ item.name }}</h3>
                <div class="movie-info">
                  <span class="movie-length">{{ item.movieLength }}分钟</span>
                  <span class="movie-director">导演: {{ item.director }}</span>
                </div>
              </div>
            </div>
          </el-carousel-item>
        </el-carousel>
      </div>
      <div v-else class="preview-disabled">
        <i class="el-icon-picture-outline"></i>
        <p>预览已关闭</p>
      </div>
    </el-card>

    <!-- 轮播图列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <h3>轮播图列表</h3>
          <div class="header-actions">
            <el-button
              type="primary"
              size="small"
              @click="handleBatchOperation"
            >
              批量操作
            </el-button>
            <el-dropdown @command="handleSort">
              <el-button size="small">
                排序方式
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="name">按名称排序</el-dropdown-item>
                  <el-dropdown-item command="time">按时间排序</el-dropdown-item>
                  <el-dropdown-item command="length">
                    按时长排序
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button size="small" @click="toggleView">
              {{ isTableView ? '卡片视图' : '表格视图' }}
            </el-button>
          </div>
        </div>
      </template>

      <!-- 表格视图 -->
      <div v-if="isTableView" class="table-view">
        <el-table
          :data="filteredBannerList"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          border
          stripe
          highlight-current-row
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="序号" width="60" />
          <el-table-column label="电影封面" width="120">
            <template #default="{ row }">
              <el-image
                :src="row.photo"
                style="width: 80px; height: 120px"
                fit="cover"
                :preview-src-list="[row.photo]"
              />
            </template>
          </el-table-column>
          <el-table-column prop="name" label="电影名称" width="180" />
          <el-table-column prop="director" label="导演" width="150" />
          <el-table-column prop="movieLength" label="时长" width="80">
            <template #default="{ row }">
              <span>{{ row.movieLength }}分钟</span>
            </template>
          </el-table-column>
          <el-table-column prop="isHot" label="热门" width="80">
            <template #default="{ row }">
              <el-tag :type="row.isHot ? 'danger' : 'info'" effect="plain">
                {{ row.isHot ? '是' : '否' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="isExist" label="状态" width="80">
            <template #default="{ row }">
              <el-tag :type="row.isExist ? 'success' : 'info'" effect="dark">
                {{ row.isExist ? '已上架' : '已下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250">
            <template #default="{ row }">
              <el-button size="small" type="primary" @click="handleEdit(row)">
                编辑
              </el-button>
              <el-button
                size="small"
                :type="row.isExist ? 'danger' : 'success'"
                @click="handleToggleStatus(row)"
              >
                {{ row.isExist ? '下架' : '上架' }}
              </el-button>
              <el-button size="small" type="info" @click="handlePreview(row)">
                预览
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :total="filteredBannerList.length"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>

      <!-- 卡片视图 -->
      <div v-else class="card-view">
        <div class="banner-grid">
          <el-card
            v-for="item in paginatedBannerList"
            :key="item.id"
            class="banner-card"
            :body-style="{ padding: '0px' }"
            shadow="hover"
          >
            <div class="card-image-container">
              <el-image
                :src="item.photo"
                fit="cover"
                class="card-image"
                :preview-src-list="[item.photo]"
              />
              <div class="image-overlay">
                <el-tag type="danger" effect="dark" class="movie-length-tag">
                  {{ item.movieLength }}分钟
                </el-tag>
                <el-tag
                  v-if="item.isHot"
                  type="warning"
                  effect="dark"
                  class="movie-hot-tag"
                >
                  热门
                </el-tag>
              </div>
              <div
                class="status-badge"
                :class="{ 'status-active': item.isExist }"
              >
                {{ item.isExist ? '已上架' : '已下架' }}
              </div>
            </div>
            <div class="card-content">
              <h3 class="card-title">{{ item.name }}</h3>
              <div class="card-info">
                <p class="director">
                  <span class="label">导演:</span>
                  {{ item.director }}
                </p>
                <p class="actors">
                  <span class="label">主演:</span>
                  {{
                    item.actors.length > 15
                      ? item.actors.substr(0, 15) + '...'
                      : item.actors
                  }}
                </p>
              </div>
              <div class="card-actions">
                <el-button
                  size="small"
                  type="primary"
                  @click.stop="handleEdit(item)"
                >
                  编辑
                </el-button>
                <el-button
                  size="small"
                  :type="item.isExist ? 'danger' : 'success'"
                  @click.stop="handleToggleStatus(item)"
                >
                  {{ item.isExist ? '下架' : '上架' }}
                </el-button>
              </div>
            </div>
          </el-card>
        </div>
        <div class="pagination-container">
          <el-pagination
            background
            layout="prev, pager, next, sizes, total"
            :total="filteredBannerList.length"
            :page-size="pageSize"
            :current-page="currentPage"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑轮播图信息"
      width="50%"
      :before-close="handleDialogClose"
    >
      <el-form
        :model="editForm"
        label-width="100px"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="电影名称" prop="name">
          <el-input
            v-model="editForm.name"
            placeholder="请输入电影名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="导演" prop="director">
          <el-input
            v-model="editForm.director"
            placeholder="请输入导演姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="主演" prop="actors">
          <el-input
            v-model="editForm.actors"
            placeholder="请输入主演姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="电影时长" prop="movieLength">
          <el-input-number
            v-model="editForm.movieLength"
            :min="1"
            placeholder="请输入电影时长"
          ></el-input-number>
          <span class="unit">分钟</span>
        </el-form-item>
        <el-form-item label="是否热门">
          <el-switch
            v-model="editForm.isHot"
            active-text="是"
            inactive-text="否"
          ></el-switch>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            v-model="editForm.isExist"
            active-text="上架"
            inactive-text="下架"
          ></el-switch>
        </el-form-item>
        <el-form-item label="电影封面">
          <div class="image-preview">
            <el-image
              :src="editForm.photo"
              fit="cover"
              style="width: 100px; height: 150px"
            ></el-image>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="轮播图预览"
      width="70%"
      :before-close="handlePreviewDialogClose"
    >
      <div class="preview-dialog-content">
        <div class="preview-image-container">
          <el-image
            :src="previewData.photo"
            fit="cover"
            class="preview-image"
          ></el-image>
        </div>
        <div class="preview-info">
          <h2 class="preview-title">{{ previewData.name }}</h2>
          <div class="preview-detail">
            <p>
              <span class="label">导演:</span>
              {{ previewData.director }}
            </p>
            <p>
              <span class="label">主演:</span>
              {{ previewData.actors }}
            </p>
            <p>
              <span class="label">时长:</span>
              {{ previewData.movieLength }}分钟
            </p>
            <p>
              <span class="label">状态:</span>
              <el-tag
                :type="previewData.isExist ? 'success' : 'info'"
                effect="dark"
              >
                {{ previewData.isExist ? '已上架' : '已下架' }}
              </el-tag>
            </p>
            <p>
              <span class="label">热门:</span>
              <el-tag
                :type="previewData.isHot ? 'danger' : 'info'"
                effect="plain"
              >
                {{ previewData.isHot ? '是' : '否' }}
              </el-tag>
            </p>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 批量操作对话框 -->
    <el-dialog v-model="batchDialogVisible" title="批量操作" width="30%">
      <div class="batch-operation-content">
        <p>已选择 {{ selectedItems.length }} 项</p>
        <div class="batch-actions">
          <el-button type="primary" @click="handleBatchStatusChange(true)">
            批量上架
          </el-button>
          <el-button type="danger" @click="handleBatchStatusChange(false)">
            批量下架
          </el-button>
          <el-button type="warning" @click="handleBatchHotChange(true)">
            设为热门
          </el-button>
          <el-button @click="handleBatchHotChange(false)">取消热门</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed, reactive } from 'vue'
import { Records, Film } from '@/api/film/type.ts'
import { reqBanner, reqAddOrUpdateFilm, RequpdateFilmIsExist } from '@/api/film'
import { ElMessage, ElMessageBox } from 'element-plus'

// 数据相关
const BannerList = ref<Records>([])
const searchKeyword = ref('')
const isTableView = ref(true)
const previewEnabled = ref(true)
const currentPage = ref(1)
const pageSize = ref(8)
const selectedItems = ref<Film[]>([])

// 对话框相关
const dialogVisible = ref(false)
const previewDialogVisible = ref(false)
const batchDialogVisible = ref(false)
const editForm = ref<Film>({} as Film)
const previewData = ref<Film>({} as Film)
const formRef = ref()

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入电影名称', trigger: 'blur' }],
  director: [{ required: true, message: '请输入导演姓名', trigger: 'blur' }],
  actors: [{ required: true, message: '请输入主演姓名', trigger: 'blur' }],
  movieLength: [{ required: true, message: '请输入电影时长', trigger: 'blur' }],
}

// 初始化数据
onMounted(() => {
  getAll()
})

// 获取所有轮播图数据
const getAll = async () => {
  try {
    const result: any = await reqBanner()
    if (result.code === 200) {
      BannerList.value = result.data
    } else {
      ElMessage.error('获取轮播图数据失败')
    }
  } catch (error) {
    console.error('获取轮播图数据出错:', error)
    ElMessage.error('获取轮播图数据出错')
  }
}

// 刷新数据
const refreshData = () => {
  getAll()
  ElMessage.success('数据已刷新')
}

// 统计相关方法
const getActiveCount = () => {
  return BannerList.value.filter((item) => item.isExist).length
}

const getHotCount = () => {
  return BannerList.value.filter((item) => item.isHot).length
}

const getRecentAddedCount = () => {
  // 假设最近添加是最近7天内添加的
  return Math.floor(BannerList.value.length * 0.3) // 模拟数据，实际应该根据时间判断
}

// 搜索相关
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
}

const handleSearchClear = () => {
  searchKeyword.value = ''
}

// 过滤后的列表
const filteredBannerList = computed(() => {
  if (!searchKeyword.value) return BannerList.value

  return BannerList.value.filter(
    (item) =>
      item.name.toLowerCase().includes(searchKeyword.value.toLowerCase()) ||
      item.director.toLowerCase().includes(searchKeyword.value.toLowerCase()),
  )
})

// 分页后的列表
const paginatedBannerList = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value
  return filteredBannerList.value.slice(startIndex, startIndex + pageSize.value)
})

// 分页相关
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

// 视图切换
const toggleView = () => {
  isTableView.value = !isTableView.value
}

// 排序方法
const handleSort = (command: string) => {
  switch (command) {
    case 'name':
      BannerList.value.sort((a, b) => a.name.localeCompare(b.name))
      break
    case 'time':
      BannerList.value.sort((a, b) => b.time - a.time)
      break
    case 'length':
      BannerList.value.sort((a, b) => b.movieLength - a.movieLength)
      break
  }
  ElMessage.success(
    `已按${
      command === 'name' ? '名称' : command === 'time' ? '时间' : '时长'
    }排序`,
  )
}

// 表格选择相关
const handleSelectionChange = (val: Film[]) => {
  selectedItems.value = val
}

// 编辑相关
const handleEdit = (row: Film) => {
  editForm.value = JSON.parse(JSON.stringify(row)) // 深拷贝
  dialogVisible.value = true
}

const handleSaveEdit = async () => {
  try {
    const result = await reqAddOrUpdateFilm(editForm.value)
    if (result.code === 200) {
      ElMessage.success('保存成功')
      dialogVisible.value = false
      getAll() // 刷新数据
    } else {
      ElMessage.error(result.message || '保存失败')
    }
  } catch (error) {
    console.error('保存出错:', error)
    ElMessage.error('保存出错')
  }
}

const handleDialogClose = (done: () => void) => {
  ElMessageBox.confirm('确认关闭？未保存的数据将会丢失')
    .then(() => {
      done()
    })
    .catch(() => {})
}

// 状态切换
const handleToggleStatus = async (row: Film) => {
  try {
    if (row.isExist) {
      // 下架操作
      const result = await reqAddOrUpdateFilm({
        ...row,
        isExist: false,
      })
      if (result.code === 200) {
        ElMessage.success('下架成功')
        getAll() // 刷新数据
      } else {
        ElMessage.error(result.message || '下架失败')
      }
    } else {
      // 上架操作
      const result = await RequpdateFilmIsExist(row.id)
      if (result.code === 200) {
        ElMessage.success('上架成功')
        getAll() // 刷新数据
      } else {
        ElMessage.error(result.message || '上架失败')
      }
    }
  } catch (error) {
    console.error('操作出错:', error)
    ElMessage.error('操作出错')
  }
}

// 预览相关
const handlePreview = (row: Film) => {
  previewData.value = row
  previewDialogVisible.value = true
}

const handlePreviewDialogClose = (done: () => void) => {
  done()
}

// 批量操作相关
const handleBatchOperation = () => {
  if (selectedItems.value.length === 0) {
    ElMessage.warning('请先选择要操作的项')
    return
  }
  batchDialogVisible.value = true
}

const handleBatchStatusChange = async (status: boolean) => {
  try {
    const promises = selectedItems.value.map((item) => {
      if (status) {
        // 批量上架
        return RequpdateFilmIsExist(item.id)
      } else {
        // 批量下架
        return reqAddOrUpdateFilm({
          ...item,
          isExist: false,
        })
      }
    })

    await Promise.all(promises)
    ElMessage.success(`批量${status ? '上架' : '下架'}成功`)
    batchDialogVisible.value = false
    getAll() // 刷新数据
  } catch (error) {
    console.error('批量操作出错:', error)
    ElMessage.error('批量操作出错')
  }
}

const handleBatchHotChange = async (isHot: boolean) => {
  try {
    const promises = selectedItems.value.map((item) => {
      return reqAddOrUpdateFilm({
        ...item,
        isHot,
      })
    })

    await Promise.all(promises)
    ElMessage.success(`批量${isHot ? '设为热门' : '取消热门'}成功`)
    batchDialogVisible.value = false
    getAll() // 刷新数据
  } catch (error) {
    console.error('批量操作出错:', error)
    ElMessage.error('批量操作出错')
  }
}
</script>

<style scoped lang="scss">
.banner-manager {
  padding: 20px;
  background: #f5f7fa;
}

// 顶部卡片
.header-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .title-section {
    display: flex;
    align-items: center;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
      color: #303133;
      margin-right: 15px;
    }

    .count-tag {
      padding: 4px 8px;
    }
  }

  .action-section {
    display: flex;
    align-items: center;
    gap: 10px;

    .search-input {
      width: 220px;
    }
  }
}

// 统计卡片
.stats-section {
  margin-bottom: 20px;

  .stat-card {
    border-radius: 8px;
    overflow: hidden;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-5px);
      box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
    }

    .stat-content {
      display: flex;
      align-items: center;
      padding: 10px;
    }

    .stat-icon {
      width: 60px;
      height: 60px;
      border-radius: 50%;
      background-color: #67c23a;
      color: white;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 15px;

      i {
        font-size: 30px;
      }

      &.blue {
        background-color: #409eff;
      }

      &.orange {
        background-color: #e6a23c;
      }

      &.purple {
        background-color: #9254de;
      }
    }

    .stat-info {
      .stat-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        line-height: 1.2;
      }

      .stat-label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
}

// 预览卡片
.preview-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .carousel-container {
    padding: 20px;

    .banner-carousel {
      margin: 0 auto;

      .carousel-item {
        border-radius: 8px;
        overflow: hidden;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
        }
      }

      .carousel-content {
        position: relative;
        width: 100%;
        height: 100%;
        border-radius: 8px;
        overflow: hidden;

        .carousel-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
          transition: transform 0.5s;

          &:hover {
            transform: scale(1.05);
          }
        }

        .carousel-overlay {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          padding: 20px;
          background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
          color: #fff;

          .movie-title {
            margin: 0 0 10px 0;
            font-size: 18px;
            font-weight: bold;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
          }

          .movie-info {
            display: flex;
            justify-content: space-between;
            font-size: 14px;

            span {
              margin-right: 15px;

              &:last-child {
                margin-right: 0;
              }
            }
          }
        }
      }
    }
  }

  .preview-disabled {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    height: 300px;
    background-color: #f5f7fa;
    color: #909399;
    border-radius: 8px;

    i {
      font-size: 48px;
      margin-bottom: 10px;
    }

    p {
      font-size: 16px;
    }
  }
}
</style>
